import { createHash } from 'crypto';
import { resolve, parse } from 'path';
import { readFileSync, writeFileSync } from 'fs';

import FX from 'fs-extra';
import Moment from 'moment';

import { C } from '../../lib/global.js';
import { updateWAD } from './update.lib/updateMeta.js';
import Wog from './update.lib/lib/Wog.js';


class FileSimple {
	constructor(file) {
		this.file = file;
		this.name = parse(this.file).base;
	}

	extract() {
		const hash = createHash('md5').update(readFileSync(this.file)).digest('hex');

		return [hash, this.file];
	}
}

const method = 'get';
const handle = async function(raw, ctx, rout, $) {
	const { name } = raw;
	const pathFile = resolve(C.path.vowad, name);
	const file = parse(pathFile);
	const fileMetas = resolve(C.path.vowad, '@meta.json');


	let meta;
	try {
		meta = FX.readJSONSync(fileMetas);
	}
	catch(error) {
		meta = { unFinish: true, version: 0, time: 0 };
	}


	const base = file.base;
	const fileMeta = resolve(C.path.vowad, `${base}.meta.json`);

	let metaWADRaw;
	try { metaWADRaw = FX.readJSONSync(fileMeta); }
	catch(error) { void 0; }
	let metaWAD = await updateWAD(new FileSimple(pathFile), metaWADRaw, () => new Wog());

	writeFileSync(fileMeta, JSON.stringify(metaWAD, null, '\t'));
	meta.time = Moment().format('YYYY-MM-DD HH:mm:ss');
	writeFileSync(fileMetas, JSON.stringify(meta, null, '\t'));

	return { success: false, message: '更新正在进行' };
};


export { method, handle };
